<template>
  <div
    v-if="contextmenuConfig.show"
    ref="targetEl"
    class="contextmenu"
    :style="style"
  >
    <ul>
      <li
        v-for="(item, key) in contextmenuConfig.list"
        :key="key"
        class="flex align-center"
        :class="{ disabled: item.disabled }"
        @click="run(item)"
      >
        <div class="icon flex flex-s mr-8">
          <img width="16" :src="item.icon" />
        </div>
        <div class="title">
          {{ item.title }}
        </div>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue';
  import { onClickOutside } from '@vueuse/core';
  import { contextmenuConfig } from './bus';
  import { ContextmenuData } from './types';

  const targetEl = ref();

  const style = computed(() => {
    const el = targetEl.value as HTMLElement;
    if (el) {
      const { width, height } = el.getBoundingClientRect();
      if (window.innerWidth < width + contextmenuConfig.value.left) {
        contextmenuConfig.value.left = window.innerWidth - width;
      }
      if (window.innerHeight < height + contextmenuConfig.value.top) {
        contextmenuConfig.value.top = window.innerHeight - height;
      }
    }
    return {
      left: `${contextmenuConfig.value.left}px`,
      top: `${contextmenuConfig.value.top}px`,
    };
  });
  onClickOutside(targetEl, () => {
    contextmenuConfig.value.show = false;
  });
  const run = (item: ContextmenuData) => {
    item.action();
    contextmenuConfig.value.show = false;
  };
</script>

<style lang="scss" scoped>
  @import './style';
</style>
